package cn.edu.swu.bc.servlet;

import cn.edu.swu.bc.entity.Administrator;
import cn.edu.swu.bc.filter.AuthFilter;
import cn.edu.swu.bc.utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;


public class AdminServlet extends HttpServlet {

    private static final long serialVersionUID = 119822331124340L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            this.doPost(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String adminName = request.getParameter("admin");//获取账号密码和验证码
        String pass = request.getParameter("pass");
        String code = request.getParameter("code");
        String errorMsg = null;
        if (adminName != "" && pass != ""&& code!="") {
            String password = null;
            HttpSession session = request.getSession(true);
            Administrator admin=new Administrator();
            //从session中取出验证码
            String validateCode = (String) session.getAttribute(AuthFilter.LOGIN_VALIDATE_CODE);
            try {
                admin=DBUtils.GetAdmin(adminName);
                password=admin.getPassword();
                //通过数据库返回用户类
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            if (password != null && password.equals(pass) && validateCode.equalsIgnoreCase(code)) {
                response.sendRedirect("./u/index.html");
                //若登录成功则更改FILTER里的信息
                session.setAttribute(AuthFilter.USER_ID,admin.getID());
                session.setAttribute(AuthFilter.USER_NICKNAME,admin.getAdminName());
                session.setAttribute(AuthFilter.USER_AVATAR,null);
                session.setAttribute(AuthFilter.USER_SIGNATURE,"尊敬的管理员您好");
                session.setAttribute(AuthFilter.LOGIN_STATUS, Boolean.TRUE);
                session.setAttribute(AuthFilter.IS_ADMIN, Boolean.TRUE);
                return;
                //判断为那种登录错误并构造错误信息
            } else if (password == null) {
                errorMsg = "该管理员不存在";
            } else if (!password.equals(pass)) {
                errorMsg = "账号或密码错误";
            } else {
                errorMsg = "验证码错误";
            }
        }
        else if(adminName != "" && pass != "")
        {
            errorMsg = "请输入验证码";
        }
        else
        {
            errorMsg = "请输入用户名和密码";
        }
        request.setAttribute("errorMsg", errorMsg);
        request.getRequestDispatcher("./admin.jsp").forward(request, response);
    }
}
